﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kojarskiy.Core;
using Kojarskiy.Models;
using Microsoft.Ajax.Utilities;

namespace Kojarskiy.Controllers
{
    public class OnlineRegistrationController : Controller
    {
        private KojarskiyDbEntities context = new KojarskiyDbEntities();
        // GET: /OnlineRegistration/

        public ActionResult Index()
        {
            GetPageInfo();

            return View();
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase AuthorityFile)
        {
            try
            {
                var request = new Requests()
                {
                    CompositionName = Request.Params["CompositionName"],
                    PreviousName = Request.Params["PreviousName"],
                    Branch = Request.Params["Branch"],
                    ObjectType = Request.Params["ObjectType"],
                    FinishDate = DateTime.Parse(Request.Params["FinishDate"]),
                    PublicationInformation = Request.Params["PublicationInformation"],
                    DependencyInformation = Request.Params["DependencyInformation"],
                    OriginInformation = Request.Params["OriginInformation"],
                    IncludedInformation = Request.Params["IncludedInformation"],
                    PreviousRegistration = Request.Params["PreviousRegistration"],
                    Authority = Request.Params["Authority"],
                    CreationType = Request.Params["CreationType"] ?? "(В порядке индивидуальной разработки)",
                    Registrator = Request.Params["Registrator"] ?? "(Автор)",
                    AuthorityFile = "(Файл отсутствует)"
                };

                context.Requests.Add(request);
                context.SaveChanges();

                List<Authors> authors = GetAuthorData(Request.Params);
                foreach (var author in authors)
                {
                    author.RequestId = request.RequestId;
                    context.Authors.Add(author);
                }

                context.Entry(request).State = EntityState.Modified;
                FileHelper.UploadFile(AuthorityFile, "Authority", request.RequestId);

                context.SaveChanges();

                GetPageInfo();
                return View("Payment", request);
            }
            catch (DbEntityValidationException ex)
            {
                string errorString = "Извините, произошла ошибка выполнения операции: ";
                foreach (DbEntityValidationResult validationResult in ex.EntityValidationErrors)
                {
                    string entityName = validationResult.Entry.Entity.GetType().Name;
                    foreach (DbValidationError error in validationResult.ValidationErrors)
                    {
                        errorString += entityName + "." + error.PropertyName + ": " + error.ErrorMessage + "<br/>";
                    }
                }

                KojarskiyApplication.Log(KojarskiyApplication.ErrorType.Fatal, errorString, ex.StackTrace);
                GetPageInfo();
                return View();
            }
            catch (Exception ex)
            {
                KojarskiyApplication.Log(KojarskiyApplication.ErrorType.Fatal, ex.Message, ex.StackTrace);
                GetPageInfo();
                return View();
            }
        }

        public ActionResult Payment()
        {
            GetPageInfo();
            return View(context.Requests.First());
        }
        public ActionResult Result()
        {
            GetPageInfo();
            return View();
        }
        public void GetPageInfo()
        {
            var siteMap = context.SiteMap.First(x => x.Controller == "OnlineRegistration" && x.Action == "Index");
            ViewData["SiteMap"] = siteMap;
            var block = context.Blocks.FirstOrDefault(x => x.SiteMapId == siteMap.SiteMapId);
            if (block != null)
            {
                ViewData["PageBlocks"] = block.Layout;
            }

            ViewBag.Title = siteMap.Title;
            ViewBag.Description = siteMap.Description;
            ViewBag.Keywords = siteMap.Keywords;
        }

        public List<Authors> GetAuthorData(NameValueCollection data)
        {
            try
            {
                int indexer = 0;
                int count = data.AllKeys.Count(x => x.Contains("Surname"));
                var authors = new Authors[count];

                for (int i = 0; i < count; i++)
                {
                    authors[i] = new Authors();
                }

                foreach (var key in data.AllKeys)
                {
                    int id = -1;
                    if(key.Split('-').Length == 2)
                    {
                        if (!string.IsNullOrEmpty(key.Split('-')[1])) id = Convert.ToInt32(key.Split('-')[1]);
                    }

                    var author  = authors.FirstOrDefault(x => x.RequestId == id);

                    if(author == null)
                    {
                        authors[indexer].RequestId = id;
                        author = authors[indexer];
                        indexer++;
                    }

                    if (key.Contains("Surname")) author.Surname = data[key] ?? "(не указана)";
                    if (key.Contains("FirstName")) author.FirstName = data[key] ?? "(не указано)";
                    if (key.Contains("LastName")) author.LastName = data[key] ?? "(не указано)";
                    if (key.Contains("NickName")) author.NickName = data[key] ?? "(отсутствует)";

                    if (key.Contains("BirthDate"))
                    {
                        try
                        {
                            author.BirthDate = DateTime.Parse(data[key]);
                        }
                        catch (Exception ex)
                        {
                            author.BirthDate = DateTime.Now;
                            KojarskiyApplication.Log(KojarskiyApplication.ErrorType.Fatal, ex.Message, ex.StackTrace);
                        }
                    }

                    if (key.Contains("Email")) author.Email = data[key] ?? "(не указан)";
                    if (key.Contains("Phone")) author.Phone = data[key] ?? "(не указан)";
                    if (key.Contains("Address")) author.Address = data[key] ?? "(не указан)";
                    if (key.Contains("Citizenship")) author.Citizenship = data[key] ?? "(украинское)";
                }

                return authors.ToList();
            }
            catch (Exception ex)
            {
                KojarskiyApplication.Log(KojarskiyApplication.ErrorType.Fatal, ex.Message, ex.StackTrace);
            }
            return new List<Authors>();
        }
        
        [HttpPost]
        public ActionResult PaymentCallback()
        {
            var values = Request.Form;
            GetPageInfo();
            return View("Result");
        }

        [HttpPost]
        public ActionResult AuthorForm(string blockId)
        {
            return PartialView("_Author", blockId);
        }
    }
}
